package com.blb.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用http请求调用后台服务器接口
 */
public class HttpCURDDemo {

    /**
     * 测试get请求
     */
    public void testGetQuery(){
        try {
            URL url = new URL("http://localhost:8080/person/188");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方法
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(2000);
            if(conn.getResponseCode() == 200){
                //用字符流读取响应内容
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))){
                    String line = null;
                    while((line = reader.readLine()) != null){
                        System.out.println(line);
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试post请求
     */
    public void testPostQuery(){
        try {
            URL url = new URL("http://localhost:8080/person");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方法
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(2000);
            //设置进行输出
            conn.setDoOutput(true);
            //设置内容类型
            conn.addRequestProperty("Content-Type","application/json");
            //用输出流发参数内容
            String person = "{\"id\":188,\"name\":\"张珊珊\",\"age\":20,\"gender\":\"女\"}";
            conn.getOutputStream().write(person.getBytes());
            if(conn.getResponseCode() == 200){
                //用字符流读取响应内容
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))){
                    String line = null;
                    while((line = reader.readLine()) != null){
                        System.out.println(line);
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HttpCURDDemo demo = new HttpCURDDemo();
        demo.testGetQuery();
//        demo.testPostQuery();
    }
}
